<template>
    <div>
        <el-container :style="{ height: containerHeight - 50 + 'px' }">
            <!-- 左侧菜单  部门树-->
            <el-aside width="230px" class="el-aside">
                <el-tree :data="treeData" node-key="id" default-expand-all :props="defaultProps"
                    :expand-on-click-node="false" @node-click="handleNodeClick" :highlight-current="true"></el-tree>
            </el-aside>
            <!-- 右侧内容 -->
            <el-main>
                <!-- 查询表单 -->
                <el-form :inline="true" :model="userModle" size="small" label-width="100px">
                    <el-form-item>
                        <el-input v-model="userModle.username" placeholder="请输入用户账号"
                            style="width: 140px;margin-left: 15px;"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="userModle.realname" placeholder="请输入真实姓名" style="width: 140px;"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="userModle.nickname" placeholder="请输入用户昵称" style="width: 140px;"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="userModle.pnone" placeholder="请输入手机号" style="width: 140px;"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="userModle.email" placeholder="请输入邮箱" style="width: 140px;"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch()" icon="el-icon-search"
                            style="margin-left: 15px;">查询</el-button>
                        <el-button type="danger" @click="handleReset()" icon="el-icon-refresh">重置</el-button>
                        <el-button type="success" @click="handleAdd()" icon="el-icon-plus">新增</el-button>
                        <el-button type="warning" @click="handleDeleteBatch()" icon="el-icon-delete">删除选中</el-button>
                    </el-form-item>
                </el-form>
                <!-- 数据表格 -->
                <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="40"></el-table-column>
                    <el-table-column label="序号" width="50">
                        <template slot-scope="scope">
                            {{ (start - 1) * size + scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="username" label="用户账号" width="80"></el-table-column>
                    <el-table-column prop="realname" label="真实姓名" width="80"></el-table-column>
                    <el-table-column prop="nickname" label="用户昵称" width="95"></el-table-column>
                    <el-table-column prop="pnone" label="手机号码" width="120"></el-table-column>
                    <el-table-column prop="gender" label="用户性别" width="80">
                        <template slot-scope="scope">
                            <el-tag v-if="scope.row.gender == 1" type="success">男</el-tag>
                            <el-tag v-else-if="scope.row.gender == 2" type="danger">女</el-tag>
                            <el-tag v-else>未知</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="deptName" label="所在部门" width="150"></el-table-column>
                    <el-table-column prop="email" label="用户邮箱" width="180"></el-table-column>
                    <el-table-column prop="avatar" label="用户头像" width="90">
                        <template slot-scope="scope">
                            <img :src="scope.row.avatar" width="60px" height="55px">
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                            <el-button type="success" size="mini" @click="handleRole(scope.row)">绑定角色</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination background layout="total,prev, pager, next,jumper" :current-page="start"
                    :page-size="size" :total="total" @current-change="search" style="margin-top: 15px;"></el-pagination>
                <!--新增和修改用户弹出框-->
                <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogVisible" width="40%">
                    <el-form :model="saveUser" :rules="rules" ref="form" label-width="80px" :inline="true">
                        <el-form-item label="所在部门" prop="deptName">
                            <el-input v-model="saveUser.deptName" :readonly="true" ref="deptName"
                                @click.native="openDeptSelect"></el-input>
                        </el-form-item>
                        <el-form-item label="用户账号" prop="username">
                            <el-input v-model="saveUser.username" placeholder="请输入用户账号"></el-input>
                        </el-form-item>
                        <el-form-item label="用户密码" prop="password" v-if="dialogStatus === 'create'">
                            <el-input v-model="saveUser.password" type="password" placeholder="请输入用户密码"></el-input>
                        </el-form-item>
                        <el-form-item label="真实姓名" prop="realname">
                            <el-input v-model="saveUser.realname" placeholder="请输入真实姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="用户昵称" prop="nickname">
                            <el-input v-model="saveUser.nickname" placeholder="请输入用户昵称"></el-input>
                        </el-form-item>
                        <el-form-item label="用户电话" prop="pnone">
                            <el-input v-model="saveUser.pnone" placeholder="请输入用户电话"></el-input>
                        </el-form-item>
                        <el-form-item label="电子邮箱" prop="email">
                            <el-input v-model="saveUser.email" placeholder="请输入电子邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="用户性别" prop="gender">
                            <el-radio-group v-model="saveUser.gender">
                                <el-radio-button label="1">男</el-radio-button>
                                <el-radio-button label="2">女</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="用户头像" prop="avatar">
                            <el-upload class="avatar-uploader" :action="uploadPath"
                                :show-file-list="false" :on-success="handleavatarSuccess"
                                :before-upload="beforeavatarUpload" :data="uploadToken">
                                <img v-if="saveUser.avatar" :src="saveUser.avatar" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary"
                            @click="dialogStatus === 'create' ? createData() : updateData()">确定</el-button>
                    </div>
                </el-dialog>
                <!-- 所在部门弹窗 -->
                <el-dialog title="所在部门" :visible.sync="dialogDeptVisible" width="30%">
                    <el-tree :data="treeData" node-key="id" ref="tree" highlight-current @node-click="handleDeptSelect"
                        :default-expand-all="true" :props="defaultProps">
                    </el-tree>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="clearSelect">取 消</el-button>
                        <el-button type="primary" @click="handleDeptConfirm">确 定</el-button>
                    </span>
                </el-dialog>
                <!-- 绑定角色弹窗 -->
                 <el-dialog title="绑定角色" :visible.sync="dialogRoleVisible">
                    <el-checkbox-group v-model="roleIds">
                        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
                            {{item.roleName}}
                        </el-checkbox>
                    </el-checkbox-group>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="clearBind">取 消</el-button>
                        <el-button type="primary" @click="handleBindRole">确 定</el-button>
                    </div>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>

<script>
import deptUtil from '@/api/dept';
import UserUtil from '@/api/auth_user';
import { getToken } from '@/utils/auth';
import roleUtil from '@/api/auth_role';
export default {
    data() {
        return {
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'deptName'
            },
            containerHeight: 0,
            userModle: {},
            tableData: [],
            start: 0,
            size: 5,
            total: 0,
            titleMap: {
                create: '新增用户',
                update: '修改用户'
            },
            dialogStatus: 'create',
            dialogVisible: false,
            saveUser: {},
            mutipleSelection: [],
            dialogDeptVisible: false,
            treeData: [],
            defaultProps: {
                label: 'deptName',
                children: 'children'
            },  
            uploadPath: process.env.VUE_APP_BASE_API+'rental/oss/upload',
            uploadToken: { token: getToken() },
            dialogRoleVisible: false,
            roleIds: [],
            roleList: [],
            userId: 0,
            rules: {
                deptName: [
                    { required: true, message: '请选择部门', trigger: 'blur' }
                ],
                username: [
                    { required: true, message: '请输入用户账号', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入用户密码', trigger: 'blur' }
                ],
                realname: [
                    { required: true, message: '请输入真实姓名', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入用户电话', trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'blur' }
                ]
            }

        }
    },
    created() {
        this.getTreeData();
        this.search();
    },
    mounted() {
        this.containerHeight = document.documentElement.clientHeight - 50
    },
    methods: {
        async getTreeData() {
            const res = await deptUtil.selectTree()
            if (res.success) {
                this.treeData = res.data
            }
        },
        async search(start = 1) {
            this.start = start;
            await UserUtil.search(this.start, this.size, this.userModle).then(res => {
                if (res.success) {
                    this.tableData = res.data.records;
                    this.total = res.data.total;
                }
            })
        },
        handleNodeClick(data) {
            this.userModle.deptId = data.id;
            this.search();
        },
        handleAdd() {
            this.dialogStatus = 'create'
            this.dialogVisible = true
            this.saveUser = {}
            this.$nextTick(() => {
                this.$refs['form'].clearValidate()
            })
        },
        handleDelete(row) { 
            if(row.isAdmin==1){
                this.$message.error('超级管理员不允许删除');
            }else{
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const res = await UserUtil.delete(row.id);
                    if (res.success) {
                        this.$message.success('删除用户成功');
                        this.search();
                    }
                })
            }
        },
        handleSelectionChange(val) { 
            this.mutipleSelection = [];
            val.forEach(element => {
                this.mutipleSelection.push(element.id)
            });
        },
        handleDeleteBatch() {
            if(this.mutipleSelection.length==0){
                this.$message.error('请选择要删除的数据');
                return;
            }
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const res = await UserUtil.delete(this.mutipleSelection);
                if (res.success) {
                    this.$message.success('已删除非超级管理员!');
                    this.search();
                }
            })
        },
        handleEdit(row) {
            this.dialogStatus = 'update';
            this.saveUser = row;
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.$refs['form'].clearValidate()
            });
        },
        handleReset() {
            this.userModle = {},
                this.search();
        },
        handleSearch() {
            this.search();
        },
        openDeptSelect() {
            this.dialogDeptVisible = true;
            deptUtil.selectTree().then(res => {
                if (res.success) {
                    this.deptTree = res.data;
                }
            })
        },
        handleDeptSelect(data) {
            this.saveUser.deptId = data.id;
            this.saveUser.deptName = data.deptName;
        },
        createData() {
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    let res = await UserUtil.save(this.saveUser);
                    if (res.success) {
                        this.$message({
                            type: 'success',
                            message: '新增成功'
                        });
                        this.dialogVisible = false;
                        this.search();
                    }
                }
            })
        },
        updateData() {
            this.$refs['form'].validate(async (valid) => {
                if (!valid) {
                    return false;
                } else {
                    const res = await UserUtil.update(this.saveUser);
                    if (res.success) {
                        this.$message({
                            type: 'success',
                            message: '修改成功'
                        });
                        this.dialogVisible = false;
                        this.search();
                    }
                }
            })
        },
        clearSelect() {
            this.dialogDeptVisible = false
            this.saveUser.deptId = null;
            this.saveUser.deptName = "";
        },
        handleDeptConfirm() {
            this.dialogDeptVisible = false
            this.$refs.form.clearValidate("deptName");
        },
        handleavatarSuccess(res, file) {
            this.saveUser.avatar = res.data;
            this.$forceUpdate();
         },
        beforeavatarUpload(file) {
            const isJPG = file.type === 'image/jpeg'|| 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG或者PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        handleRole(row) { 
            this.userId = row.id;
            this.dialogRoleVisible = true;
            // 获取所有角色
            roleUtil.listRole().then(res => {
                if (res.success) {
                    this.roleList = res.data;
                }
            })
            // 获取用户已绑定的角色
            UserUtil.selectRoleByUserId(row.id).then(res => {
                if (res.success) {
                    this.roleIds = res.data;
                }
            })

        },
        clearBind(){
            this.dialogRoleVisible = false;
            UserUtil.selectRoleByUserId(this.userId).then(res => {
                if (res.success) {
                    this.roleIds = res.data;
                }
            })
        },
        handleBindRole(){
            UserUtil.bindRole(this.userId,this.roleIds).then(res => {
                if (res.success) {
                    this.$message({
                        type: 'success',
                        message: '绑定成功'
                    });
                    this.dialogRoleVisible = false;
                    this.search();
                }
            })
        }

    }
}
</script>

<style>
.el-aside {
    background-color: #fff;
    border-right: 1px solid #d5d0d0;
    border-top: 2px solid #be6868;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>